﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Keepo.Models;
using Ionic.Zip;
using System.IO;

namespace AlbumDesigner.Helpers
{
    public class PagesHelper
    {
        static public void SavePageBackup(int pageId)
        {
            try
            {
                using (var db = new AlbumContext())
                {
                    var page = db.AlbumPages.Find(pageId);

                    if (page != null)
                    {
                        var xmlFileName = HttpContext.Current.Server.MapPath("~/") + AlbumHelper.PageXmlUrl(page.AlbumSection.AlbumId, pageId);
                        
                        string dirname = Path.GetDirectoryName(xmlFileName);
                        string backupDir = dirname + "\\backup";

                        // Create "Backup" directory if not exists
                        if (Directory.Exists(dirname) && !Directory.Exists(backupDir))
                        {
                            Directory.CreateDirectory(backupDir);
                        }

                        // If file exists than back it up
                        if (File.Exists(xmlFileName))
                        {
                            string filename = Path.GetFileName(xmlFileName);
                            string dateZipSuffix = string.Format("-{0:yyyy-MM-dd_hh-mm-ss-tt}.zip", DateTime.Now);
                            var zipFileName = backupDir + "\\" + filename.Replace(".xml", dateZipSuffix);

                            using (ZipFile zip = new ZipFile())
                            {
                                // Add file with no directory structure
                                zip.AddFile(xmlFileName, "");
                                zip.Save(zipFileName);
                            }
                        }

                    }
                }
            }
            catch (Exception)
            {
                return;
            }

        }

    }
}